package frameTools;

import org.jnetpcap.Pcap;
import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.JPacketHandler;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Udp;

import dps.DpsMain;

public class FrameReaderThread extends Thread {

	private Pcap pcap;
	private int numPktsToRead;
	
	/**
	 * Thread that simply reads and handles packets from an already open
	 * interface (Pcap)
	 * 
	 * @param pcap
	 *            the open live source
	 * @param numPktsToRead
	 *            num pkts to read before dumping
	 */
	public FrameReaderThread(Pcap pcap, int numPktsToRead) {
		this.pcap = pcap;
		this.numPktsToRead = numPktsToRead;
	}

	public void run() {
		while (true) {
			/**
			 * Read and log incoming (and outgoing?) frames
			 */
			// Create an anonymous packet handler to read packets
			JPacketHandler<String> jpacketHandler = new JPacketHandler<String>() {
				public void nextPacket(JPacket packet, String user) {

					Ip4 ip = new Ip4();
					if (packet.hasHeader(ip))
					{
						// Do not add our added network traffic from
						// polling to the local history.  We define our
						// traffic as arriving on LOCAL_PORT.
						boolean add = true;
						Udp udp = new Udp();
						if (packet.hasHeader(udp)) {
							if(DpsMain.LOCAL_PORT == udp.destination())
								add = false;
						}
//						System.out.println("Source IP = "
//								+ FormatUtils.ip(ip.source()));
						if(add)
							DpsMain.addPacket(packet);
					}
					
//					System.out.println(packet.toString());
				}
			};

			// blocking call
			pcap.loop(numPktsToRead, jpacketHandler, "jNetPcap");
		}
	}
}
